package com.rainy.generator.controller;

import com.rainy.generator.common.util.ResultUtil;
import com.rainy.generator.entity.PathEntity;
import com.rainy.generator.entity.PathQuery;
import com.rainy.generator.entity.TableQuery;
import com.rainy.generator.manager.GeneratorManager;
import com.rainy.generator.service.PathService;
import com.rainy.generator.service.TableService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author liuqin on 2017/12/16
 */
@RequestMapping("/table")
@Controller
public class TableController {
    @Resource
    private TableService tableService;

    @Resource
    private PathService pathService;

    @Resource
    private GeneratorManager generatorManager;

    @ResponseBody
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public Object list(String dbName,String tableName,Long page,Long limit){
        TableQuery tableQuery = new TableQuery();
        tableQuery.setDbName(dbName);
        tableQuery.setTableName(tableName);
        if (page!=null && limit!=null) {
            tableQuery.setOffset((page - 1) * limit);
            tableQuery.setLimit(limit);
        }
        return ResultUtil.toJsonResult(tableService.queryTables(tableQuery),tableService.queryCount(tableQuery));
    }

    @RequestMapping("")
    public Object list(ModelMap modelMap,String dbName){
        String connectDb = tableService.getConnectDb();
        modelMap.put("connectDb",connectDb);
        modelMap.put("dbs",tableService.queryDataBases());
        PathQuery pathQuery = new PathQuery();
        pathQuery.setDbName(dbName);
        pathQuery.setState(1);
        List<PathEntity> pathEntities=pathService.queryPaths(pathQuery);
        modelMap.put("paths",pathEntities);
        return "table";
    }


    @ResponseBody
    @RequestMapping(value = "generate")
    public void generate(String db,String tableName,Long pathId,HttpServletResponse response) throws IOException{

        byte[] data = generatorManager.execute(db,tableName.split(","),pathId);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"rainy.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
